package com.bawei.solr;

import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.Group;
import org.apache.solr.client.solrj.response.GroupCommand;
import org.apache.solr.client.solrj.response.GroupResponse;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

/**
 * 
 * group 分组代码演示
 *D:\apache-tomcat-7.0.68_solr\bin
 */

public class GroupTest {

	public static void main(String[] args) throws SolrServerException {

		String solrUrl = "http://localhost:8080/solr/mycore";
		HttpSolrClient client = new HttpSolrClient(solrUrl);

		SolrQuery query = new SolrQuery();

		query.setQuery("*:*");
//		query.setQuery("height:170");
		query.setParam("group", true);// 是否分组
		
//		query.setParam("group.field", "age");// 分组的域
		query.add("group.field", "height" );
//		query.add("group.query", "height:180");
		
		
		query.setParam("group.offset", "0");
		query.setParam("group.limit", "10");// 每组显示的个数，默认为1

//		query.setParam("group.sort", "height asc"); // 组内数据的排序
//		query.setParam("sort", "age asc"); // 组的排序

//		query.setParam("group.main", "true");
		
		query.setStart(0);
		query.setRows(10);	//设置了查询的分组数
		QueryResponse response = null;

		System.out.println(query);
		response = client.query(query);

		GroupResponse groupResponse = response.getGroupResponse();

		if (groupResponse != null) {

			List<GroupCommand> groupList = groupResponse.getValues();

			for (GroupCommand groupCommand : groupList) {
				List<Group> groups = groupCommand.getValues();
				System.out.println("有几个分组" + groups.size());
				System.out.println("查询到的doc总个数：" + groupCommand.getMatches());

				for (Group group : groups) {
					SolrDocumentList results = group.getResult();
					System.out.println("每个分组条数--------");
					for (SolrDocument doc : results) {
						System.out.println(doc);
					}
				}
			}
		}

	}
}
